# -*- coding: utf-8 -*- 
"""
@Author: 孟颖
@email: 652044581@qq.com
@date: 2023/4/28 11:16
@desc:  socket 收发消息
"""
from threading import Lock
import socket
import  threading


class SingletonMeta(type):
    """元类单例"""
    __instance = None
    __lock = Lock()

    def __call__(cls, *args, **kwargs):
        with cls.__lock:
            new = kwargs.pop('new', None)
            if new is True:
                return super().__call__(*args, **kwargs)
            if not cls.__instance:
                cls.__instance = super().__call__(*args, **kwargs)
        return cls.__instance


class MySocketClient(metaclass=SingletonMeta):

    def __init__(self, host=None, port=None):
        self.host = host
        self.port = port
        self.sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sk.connect((host, port))

    def send_message(self, message):
        self.sk.send(message.encode('utf-8'))

        return self.sk.recv(1024).decode()


class SocketHandler(object):
    """具体业务的实现"""
    def __init__(self,message):
        self.message = message


    def run(self):
        """处理你的业务"""
        return  self.message



class MySocketServer:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(5)

    def handle_client(self, client_socket, address):
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            print(f"Received data from {address}: {data.decode()}")
            res = SocketHandler(data).run()
            client_socket.sendall(res)
        client_socket.close()

    def start(self):
        print(f"Server listening on {self.host}:{self.port}")
        while True:
            client_socket, address = self.server_socket.accept()
            print(f"Accepted connection from {address}")
            client_thread = threading.Thread(target=self.handle_client, args=(client_socket, address))
            client_thread.start()


if __name__ == '__main__':
    # 启动服务端
    server = MySocketServer("192.168.3.87", 18082)
    server.start()


    # 启动客户端
    # host = "192.168.3.87"
    # port = 18082
    # print(MySocketClient(host=host, port=port).send_message("hello world"))

    # 不可同时运行
